/**
 * 客户端API工具
 * 用于在客户端组件中调用服务端API
 */

// API响应类型
interface ApiResponse<T = unknown> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
  pagination?: {
    limit: number;
    offset: number;
    total: number;
    category?: string;
    keyword?: string;
  };
}

// 视频数据类型
export interface Video {
  id: string;
  title: string;
  coverUrl?: string;
  durationSeconds: number;
  category: string;
  description?: string;
  sourceUrl?: string;
  publishedAt?: string;
  createdAt: string;
  updatedAt: string;
}

// 分类数据类型
export interface Category {
  id: string;
  name: string;
  description?: string;
  videoCount: number;
  createdAt: string;
  updatedAt: string;
}

// 视频服务类
export class VideoApiService {
  private static baseUrl = '/api/videos';

  /**
   * 获取所有视频
   */
  static async getAllVideos(limit = 20, offset = 0): Promise<ApiResponse<Video[]>> {
    try {
      const response = await fetch(`${this.baseUrl}?limit=${limit}&offset=${offset}`);
      return await response.json();
    } catch (error) {
      console.error('获取视频列表失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 根据ID获取视频
   */
  static async getVideoById(id: string): Promise<ApiResponse<Video>> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`);
      return await response.json();
    } catch (error) {
      console.error('获取视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 根据分类获取视频
   */
  static async getVideosByCategory(category: string, limit = 20, offset = 0): Promise<ApiResponse<Video[]>> {
    try {
      const response = await fetch(`${this.baseUrl}/category?category=${encodeURIComponent(category)}&limit=${limit}&offset=${offset}`);
      return await response.json();
    } catch (error) {
      console.error('获取分类视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 搜索视频
   */
  static async searchVideos(keyword: string, limit = 20, offset = 0): Promise<ApiResponse<Video[]>> {
    try {
      const response = await fetch(`${this.baseUrl}/search?keyword=${encodeURIComponent(keyword)}&limit=${limit}&offset=${offset}`);
      return await response.json();
    } catch (error) {
      console.error('搜索视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 添加视频
   */
  static async addVideo(videoData: {
    id: string;
    title: string;
    coverUrl?: string;
    durationSeconds?: number;
    category: string;
    description?: string;
    sourceUrl?: string;
    publishedAt?: string;
  }): Promise<ApiResponse> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(videoData),
      });
      return await response.json();
    } catch (error) {
      console.error('添加视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 更新视频
   */
  static async updateVideo(id: string, updateData: Partial<{
    title: string;
    coverUrl: string;
    durationSeconds: number;
    category: string;
    description: string;
    sourceUrl: string;
    publishedAt: string;
  }>): Promise<ApiResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData),
      });
      return await response.json();
    } catch (error) {
      console.error('更新视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 删除视频
   */
  static async deleteVideo(id: string): Promise<ApiResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/${id}`, {
        method: 'DELETE',
      });
      return await response.json();
    } catch (error) {
      console.error('删除视频失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}

// 分类服务类
export class CategoryApiService {
  private static baseUrl = '/api/categories';

  /**
   * 获取所有分类
   */
  static async getAllCategories(): Promise<ApiResponse<Category[]>> {
    try {
      const response = await fetch(this.baseUrl);
      return await response.json();
    } catch (error) {
      console.error('获取分类列表失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 添加分类
   */
  static async addCategory(name: string, description?: string): Promise<ApiResponse> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, description }),
      });
      return await response.json();
    } catch (error) {
      console.error('添加分类失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}

// 数据库管理服务类
export class DatabaseApiService {
  private static baseUrl = '/api/db';

  /**
   * 测试数据库连接
   */
  static async testConnection(): Promise<ApiResponse<{ connected: boolean }>> {
    try {
      const response = await fetch(`${this.baseUrl}/init`);
      return await response.json();
    } catch (error) {
      console.error('测试数据库连接失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }

  /**
   * 初始化数据库
   */
  static async initializeDatabase(): Promise<ApiResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/init`, {
        method: 'POST',
      });
      return await response.json();
    } catch (error) {
      console.error('初始化数据库失败:', error);
      return {
        success: false,
        message: '网络请求失败',
        error: error instanceof Error ? error.message : '未知错误'
      };
    }
  }
}

// 导出所有服务
export {
  VideoApiService as VideoService,
  CategoryApiService as CategoryService,
  DatabaseApiService as DatabaseService
};
